<?php
/**
 * Gallery
 *
 * @package
 * @author kubicek
 * @copyright Copyright (c) 2010
 * @version $Id$
 * @access public
 */
class Gallery extends Plugin
{
	public $plugin_name = "Gallery"; //name of plugin
	public $plugin_short_desc = "Gallery for images"; //short description of plugin
	public $plugin_long_desc = "Gallery with support of jQuery Lightbox, needs Uploadify plugin"; //longer description - what does plugin do
	public $version = "1.0"; //version of plugin
	public $has_sidebar = true; //does this plugin have sidebar -> function generate_sidebar()
	public $has_footer = true; //does this plugin have footer -> function generate_footer()
	public $needs_install = true;

	/**
	 * Constructor
	 */
	function __construct()
	{
		global $theme;
		$theme->set_title('Gallery'); //set page <title>
	}

	/**
	 * Gallery::generate_sidebar()
	 * Generate simple sidebar
	 * @return
	 */
	public function generate_sidebar()
	{
		global $core,$theme;

		$query = mysql_query("SELECT * FROM ".DB_PREFIX."yaps_gallery_sections ORDER BY name ASC");
		if(mysql_num_rows($query) > 0)
		{
			$out = '<ul>';
			while($section = mysql_fetch_array($query))
			{
				$out .= '<li><a href="gallery-section-'.$section['id'].'-'.$core->encode_url($section['name']).'">'.$section['name'].'('.$section['photo_count'].')</a></li>';
			}
			$out .= '</ul>';
		}

		$theme->assign('sidebar',$out);
	}

	/**
	 * Gallery::generate_footer()
	 * Generate simple footer
	 * @return
	 */
	public function generate_footer()
	{
		global $theme;

		$theme->assign('footer','Newest images!');
	}

	/**
	 * Gallery::start()
	 * Default function for plugin output, when there is nothing else to call
	 * @return
	 */
	public function start()
	{
		global $core;

		echo '<h1>Gallery</h1>';

		$query = mysql_query("SELECT * FROM ".DB_PREFIX."yaps_gallery_sections ORDER BY name ASC");
		if(mysql_num_rows($query) > 0)
		{
			while($section = mysql_fetch_array($query))
			{
				$query_img = mysql_query("SELECT * FROM ".DB_PREFIX."yaps_gallery_images WHERE section = ".$section['id']." ORDER BY RAND() LIMIT 0,1");
				if(mysql_num_rows($query_img) > 0)
				{
					$rnd_img = mysql_fetch_array($query_img);
				}
				else
				{
					$rnd_img = '';
				}
				echo '<div class="gallery_section"><a href="gallery-section-'.$section['id'].'-'.$core->encode_url($section['name']).'"><img src="'.WEB_URL.$rnd_img['thumb'].'" alt="'.$section['name'].'" /><br />'.$section['name'].'('.$section['photo_count'].')</a></div>';
			}
			echo '<div style="clear: both;"></div>';
		}
	}

	public function show_section()
	{
		global $core,$theme;

		$theme->include_jquery();
		$theme->include_css($this->get_plugin_path().'files/jquery.fancybox-1.3.1.css');
		$theme->include_js($this->get_plugin_path().'files/jquery.fancybox-1.3.1.pack.js');
		$theme->include_js($this->get_plugin_path().'files/jquery.mousewheel-3.0.2.pack.js');
		$theme->js('$("a[rel=gallery]").fancybox({\'titlePosition\' : \'over\'});');

		$query = mysql_query("SELECT * FROM ".DB_PREFIX."yaps_gallery_images WHERE section = ".$core->router_id." ORDER BY position ASC");
		if(mysql_num_rows($query) > 0)
		{
			while($image = mysql_fetch_array($query))
			{
				echo '<div class="gallery_section"><a href="'.WEB_URL.$image['file'].'" rel="gallery" title="'.$image['name'].' - '.$image['title'].'"><img src="'.WEB_URL.$image['thumb'].'" alt="'.$image['name'].'" /><br />'.$image['name'].'</a></div>';
			}
			echo '<div style="clear: both;"></div>';
		}
		else
		{
			$core->err('No images in this gallery :(');
		}
	}

	private function do_post_stuff()
	{
		global $core;

		if($core->post('section'))
		{
			$_SESSION['gallery_section'] = $core->post('section');
			$section = mysql_fetch_array(mysql_query("SELECT * FROM ".DB_PREFIX."yaps_gallery_sections WHERE id = ".$core->post('section')));
			$_SESSION['gallery_section_array'] = $section;

			$core->msg('You have selected section: '.$section['name']);
			$core->refresh_js('admin-pluginsettings?plugin=gallery');
		}
		elseif($core->post('images_section'))
		{
			$names = $core->post('name');
			$titles = $core->post('title');
			$ids = $core->post('id');

			for($i = 0; $i < sizeof($ids); $i++)
			{
				$query = mysql_query("UPDATE ".DB_PREFIX."yaps_gallery_images SET name = '".$core->hsc($names[$i])."', title = '".$core->hsc($titles[$i])."' WHERE id = ".$ids[$i]);
			}

			$core->msg('Images has been edited successfully!');
			$core->refresh_js('admin-pluginsettings?plugin=gallery');
		}
	}

	/**
	 * Gallery::admin_settings()
	 * Administration settings of plugin, if you can`t administrate anything it`s good to place some example of usage here
	 * It will be printed in administration of Yaps!
	 * @return
	 */
	public function admin_settings()
	{
		global $core,$theme;

		$this->do_post_stuff();

		if(!$core->is_plugin('uploadify'))
		{
			$core->err('It seems that you dont have Uploadify plugin in Yaps! Install it first so you can upload your images.');
			return;
		}

		$theme->include_jquery();
		$theme->include_css($this->get_plugin_path().'files/jquery.fancybox-1.3.1.css');
		$theme->include_js($this->get_plugin_path().'files/jquery.fancybox-1.3.1.pack.js');
		$theme->include_js($this->get_plugin_path().'files/jquery.mousewheel-3.0.2.pack.js');
		$theme->js('$("a[rel=gallery]").fancybox();');
		$theme->js('$("div.hidden").hide(); //graceful degradation

		$("h3").bind(\'click\', function (e) {
		var div = $(this).next();
		$(div).toggle("fast");
		if($(this).html().substr(0,1) == \'+\')
		{
			var length = $(this).html().length;
			$(this).html(\'-\' + $(this).html().substr(1, length - 1));
		}
		else
		{
			var length = $(this).html().length;
			$(this).html(\'+\' + $(this).html().substr(1, length - 1));
		}
		});

		$("h4").bind(\'click\', function (e) {
		var div = $(this).next();
		$(div).toggle("fast");});

		$("div.gallery").sortable({items: \'div.gallery_image\'});

		$("div.gallery").bind("sortupdate", function(event, ui)
		{
  		var list = $("div.gallery_image");
  		var sorted_list = \'\';

  		for(i = 0; i < list.length; i++ )
			{
				sorted_list += $(list[i]).attr("id") + "#";
			}

			$.get("'.$this->get_plugin_path().'ajax.php", {image_list: sorted_list}, function(data)
			{
				$("#status").html("Sorting saved!");
			});
		});');

		$theme->js('function delete_image(id,hash)
		{
			$.get("'.$this->get_plugin_path().'ajax.php", {image_id: id, image_hash: hash}, function(data)
			{
				$("#i" + id).slideUp("slow");
			});
		}',false);

		echo '<div id="status"></div>
					<h3>-Insert new images</h3><div>
					<p>Choose a section for images</p>
					<form action="" method="post">';

						$query = mysql_query("SELECT * FROM ".DB_PREFIX."yaps_gallery_sections ORDER BY name ASC");
						if(mysql_num_rows($query) > 0)
						{
							echo '<select name="section">';
							while($row = mysql_fetch_array($query))
							{
								echo '<option value="',$row['id'],'" ',($row['id'] == $_SESSION['gallery_section']) ? 'selected="selected"' : '','>',$row['name'],'</option>';
							}
							echo '</select>
										<input type="submit" value="Choose this" />';
						}
						else
						{
							echo 'You dont have any section, please insert one before uploading images.';
						}

		echo	 '</form>';

		if($_SESSION['gallery_section'])
		{
			echo '<p>Selected section: <strong>',$_SESSION['gallery_section_array']['name'],'</strong></p>';

			$upload = $core->load_plugin('uploadify');
			$upload->upload_dir = GALLERY_DIR.$_SESSION['gallery_section_array']['dir'];
			$upload->gallery_section = $_SESSION['gallery_section'];
			$upload->create_upload();
		}

		echo '</div><h3>-Images</h3><div>';

		if($_SESSION['gallery_section'])
		{
			$query = mysql_query("SELECT * FROM ".DB_PREFIX."yaps_gallery_sections WHERE id = ".$_SESSION['gallery_section_array']['id']);

			if(mysql_num_rows($query) > 0)
			{
				while($section = mysql_fetch_array($query))
				{
					echo '<h4>',$section['name'],'(',$section['photo_count'],')</h4>';

					$query_2 = mysql_query("SELECT * FROM ".DB_PREFIX."yaps_gallery_images WHERE section = ".$section['id']." ORDER BY position ASC");
					if(mysql_num_rows($query_2) > 0)
					{
						echo '<div class="gallery"><form action="" method="post">';
						$i = 0;
						while($image = mysql_fetch_array($query_2))
						{
							$hash = md5(SALT.$image['id'].SALT);
							echo '<div class="gallery_image" id="i'.$image['id'].'">
											<div class="gallery_image_image">
													<a href="'.WEB_URL.$image['file'].'" rel="gallery" title="<strong>'.$image['name'].'</strong> - '.$image['title'].'">
														<img src="'.WEB_URL.$image['thumb'].'" alt="'.$image['name'].' - '.$image['title'].'"/>
													</a>
											</div>
											<input type="text" name="name[]" value="'.$image['name'].'" /><br />
											<input type="text" name="title[]" value="'.$image['title'].'" />
											<input type="hidden" name="id[]" value="'.$image['id'].'" />
											<a href="javascript:delete_image(\''.$image['id'].'\',\''.$hash.'\')">Delete</a>
										</div>';

							$i++;
						}
						echo '<div class="cleaner"></div>';
						echo '<input type="submit" value="Edit images" /><input type="hidden" name="images_section" value="'.$section['id'].'" /></form></div>';
					}
				}
			}
		}
		else
		{
			echo 'Choose section first!';
		}

		echo '</div><h3>+Sections</h3><div class="hidden">';

		$datagrid = new Datagrid(DB_PREFIX.'yaps_gallery_sections');
		$datagrid->add_filter('id');
		$datagrid->draw_grid();

		echo '</div>';
	}

	/**
	 * Gallery::install()
	 * Installation of this plugin
	 * @return
	 */
	public function install()
	{
		$query = mysql_query("INSERT INTO ".DB_PREFIX."yaps_config VALUES ('gallery_thumb_width',125),
		('gallery_thumb_height',125),
		('gallery_max_width',1000),
		('gallery_max_height',1000),
		('gallery_dir','gallery_images/')");

		mysql_query("CREATE TABLE IF NOT EXISTS `".DB_PREFIX."yaps_gallery_images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `file` text COLLATE utf8_czech_ci NOT NULL,
  `thumb` text COLLATE utf8_czech_ci NOT NULL,
  `name` text COLLATE utf8_czech_ci NOT NULL,
  `title` text COLLATE utf8_czech_ci NOT NULL,
  `section` int(11) NOT NULL,
  `position` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci AUTO_INCREMENT=1");

		mysql_query("CREATE TABLE IF NOT EXISTS `".DB_PREFIX."yaps_gallery_sections` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` text COLLATE utf8_czech_ci NOT NULL,
  `dir` text COLLATE utf8_czech_ci NOT NULL,
  `photo_count` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci AUTO_INCREMENT=1");

		mysql_query("INSERT INTO ".DB_PREFIX."yaps_gallery_sections VALUES('0','First gallery','first/',0)");

		/* Here we will determine gallery mode. Problem is, that on some servers
		   php user cant create dirs and then upload to them. So we will try to create
		   new dir and upload some crap. If it will work, then we will create new dir
		   for every new gallery. Else we will upload all images to one dir and name them
		   section.timestamp[_thumb].ext
	  */

		mkdir('gallery/first'); //here we can assume, that gallery dir is gallery/
		@$handler = fopen('gallery/first/test','a'); //we must ignore warnings
		@fwrite($handler,'It works!');
		@fclose($handler);

		$content = file_get_contents(WEB_URL.'gallery/first/test');
		if($content == 'It works!') mysql_query("INSERT INTO ".DB_PREFIX."yaps_config VALUES ('gallery_mode','dir')");
		else
		{
			mysql_query("INSERT INTO ".DB_PREFIX."yaps_config VALUES ('gallery_mode','file')");
			rmdir('gallery/first');
		}

		mysql_query("INSERT INTO ".DB_PREFIX."yaps_config VALUES ('plugin_gallery_installed','true')");

		return true;
	}
}


?>